package com.iweb.servlet;

import com.common.context.Bean;
import com.common.context.RequestContext;
import com.common.model.DataGrid;
import com.common.model.Page;
import com.iweb.Application;
import com.iweb.controller.AdminController;
import com.common.model.HandlerUrl;
import com.common.utils.UrlUtil;
import com.iweb.pojo.Admin;
import com.iweb.utils.DataUtil;
import com.iweb.utils.JsonUtil;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@WebServlet(value = "/api/*", loadOnStartup = 1)
public class BaseServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        // 加载所有的 controller
        RequestContext context = RequestContext.getRequestContext();
        context.loadContext(Application.class);
        System.out.println(context.getBeans());
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        RequestContext requestContext = RequestContext.getRequestContext();
        req.setCharacterEncoding("utf-8");
        /*
        /api/user/login
        /api/good/findAll
        api => BaseServlet
        user => UserController
        login => UserController.login
         */
        // 解析 uri 的到 目标业务类的目标方法
        HandlerUrl handlerUrl = UrlUtil.handlerUrl(req.getRequestURI());
        Object view = null;
        // 反射 后面完成
//        if ("admin".equals(handlerUrl.getController())) {
//            AdminController controller = new AdminController();
//            if ("login".equals(handlerUrl.getMethod())) {
//                Admin admin = DataUtil.data(req, Admin.class);  // req => <T>
//                view = controller.login(admin,req);
//            }
//
//            if("findAdminList".equals(handlerUrl.getMethod())){
//                Page page = DataUtil.data(req,Page.class);
//                DataGrid<Admin> dataGrid= controller.findAdminList(page);
//                JsonUtil.writeJsonStr(resp,dataGrid);
//                view = null;
//            }
//
//            if("addAdmin".equals(handlerUrl.getMethod())){
//                Admin admin = DataUtil.data(req, Admin.class);
//                view = controller.addAdmin(admin);
//            }
//        }


        /*-----------------------*/

        try {
            // 获取controller
            Bean bean = requestContext.getBean(handlerUrl.getController());
            // 创建对象
            Object instance = bean.getClazz().newInstance();
            // 获取目标方法
            Method method = bean.getMethodMap().get(handlerUrl.getMethod());
            // 获取形参
            Class<?>[] parameterTypes = method.getParameterTypes(); // 形参
            List<Object> objects = new ArrayList<>(); // 实参

            // 封裝实参列表
            for (int i = 0; i < parameterTypes.length; i++) {
                // 确认是否传入 web 对象 request response
                if (HttpServletRequest.class.isAssignableFrom(parameterTypes[i])) {
                    objects.add(req);
                } else if (HttpServletResponse.class.isAssignableFrom(parameterTypes[i])) {
                    objects.add(resp);
                } else {
                    // 自定义形参
                    Object obj = DataUtil.data(req,parameterTypes[i]); // Admin.class
                    objects.add(obj);
                }
            }

            // 调用目标方法
            view = method.invoke(instance,objects.toArray());

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (view != null) req.getRequestDispatcher(view.toString()).forward(req, resp);

    }
}
